package com.pacvue.handler;

import com.pacvue.exception.RateLimitException;

/**
 * 默认的限流异常处理器， 实现指数退避机制。初始退避时间为500ms， 每次重试时退避时间翻倍。
 */
public class DefaultRateLimitExceptionHandler implements RateLimitExceptionHandler {

    @Override
    public void handle(RateLimitException e, String key, int retryNum) {
        // 计算指数退避时间, 初始退避时间为500ms
        long backoffTime = (long) Math.pow(2, retryNum) * 500;
        // 添加抖动算法，避免雪崩效应。抖动范围为0 ~ 200ms内
        backoffTime += (long) (Math.random() * 200);
        // 休眠
        try {
            Thread.sleep(backoffTime);
        } catch (InterruptedException ie) {
            Thread.currentThread().interrupt();
            throw new RateLimitException("Thread interrupted", ie);
        }
    }
}
